from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.admin.views.decorators import staff_member_required

from s_te.utils import delete_slug
from endo.models import Endorsement
from endo.admin.forms import EndorsementForm

@staff_member_required
def main(request, template_name="endo/admin/main.html"):
    """
    The admin endorsement listing all endorsements
    """
    endorsements = Endorsement.objects.all()
    return render_to_response(template_name, {'endorsements':endorsements, 'nav_endorsement': 'endo_admin_main'},
                              context_instance=RequestContext(request))
    
@staff_member_required
def create(request, template_name="endo/admin/create.html"):
    """
    Create a new endorsement
    """
    
    if request.POST:
        form = EndorsementForm(request.POST)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Endorsement created.")
            return HttpResponseRedirect(reverse('endo_admin_main'))
    else:
        form = EndorsementForm()
    return render_to_response(template_name, {'form':form},
                              context_instance=RequestContext(request))
    
@staff_member_required
def edit(request, slug, template_name="endo/admin/edit.html"):
    """
    Edit an existing endorsement
    """
    endorsement = get_object_or_404(Endorsement, slug=slug)
    if request.POST:
        form = EndorsementForm(request.POST, instance=endorsement)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Endorsement saved.")
            return HttpResponseRedirect(reverse('endo_admin_main'))
    else:
        form = EndorsementForm(instance=endorsement)
    return render_to_response(template_name, {'endorsement':endorsement, 'form':form},
                              context_instance=RequestContext(request))

@staff_member_required
def delete(request):
    """
    Delete an existing endorsement
    """
    delete_slug(Endorsement, request)
    request.user.message_set.create(message="Endorsement deleted.")
    return HttpResponseRedirect(reverse('endo_admin_main'))
